<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/10/25
     * Time: 13:38
     */

    namespace app\api\controller;


    use app\api\validate\IDMustBePositiveInt;
    use app\api\validate\OrderPlace;
    use app\api\service\Order as OrderService;
    use app\api\service\Token;
    use app\api\validate\PagingParameter;
    use app\api\validate\ReceiverPlace;

    use app\common\model\Order as OrderModel;

    use app\lib\exception\MissException;
    use app\lib\exception\OrderException;
    use app\lib\exception\SuccessMessage;
    use app\common\model\Account;
    use app\api\service\Refund as RefundServer;


    class Order extends BaseController
    {



        /** 帮我买 立即下单
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function placeOrder()
        {

            //dd(input("post."));
            (new OrderPlace())->goCheck();

            //$goods = input("post.goods/a");
            $data        = input('post.');
            $uid         = Token::getCurrentUid();
            $data['uid'] = $uid;
            $order       = new OrderService();
            $state       = $order->place($data);

            return $state;
        }


        /**帮我取 订单下载
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function receiverPlaceOrder()
        {
            (new ReceiverPlace())->goCheck();
            $data        = input('post.');
            $uid         = Token::getCurrentUid();
            $data['uid'] = $uid;
            $order       = new OrderService();

            $orderInfo = $order->recevierPlace($data);
            return $orderInfo;
        }


        /**
         * 获取订单通过id
         *
         * @param $id
         *
         * @return OrderModel|null
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function getOrderById($id)
        {
            (new IDMustBePositiveInt())->goCheck();

            $order =  OrderModel::where('id',$id)->with('goods,harvestAddress,pickUpGoods,pickUpAddress,weight,createOrder')->find();

            if (!$order) {
                throw new MissException(['msg' => '当前订单不存在', 'errorCode' => 60006]);
            }

            return $order;
        }


        /**
         * @param $id 大学id
         * @param $page
         * @param $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function getCanOrderable($id, $page, $size)
        {
            (new IDMustBePositiveInt())->goCheck();
            (new PagingParameter())->goCheck();
            $pagingOrders = OrderModel::getCanOrderable($id, $page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }


        /**
         * 跑男立即接单
         * 订单 状态 2->3
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function immediatelyOrder()
        {
            (new IDMustBePositiveInt())->goCheck();
            $order = (new OrderModel())->where('state', 2)->get(input('post.id'));

            if (!$order) {
                throw new MissException(['msg' => '当前订单不存在', 'errorCode' => 60006]);
            }

            //判断订单状态  是否已经被接单
//            if($order){
//
//            }




            //不能接自己发的单
            $uid = Token::getCurrentUid();
            if ($uid == $order->account_id) {

                throw new OrderException(['code' => 400, 'msg' => '不可以接自己的单哦', 'errorCode' => 60007]);

            }
            $order->order_account_id = $uid;
            $order->state            = 3;
            $order->order_time       = time();
            $order->save();
            return new SuccessMessage();

        }


        /**
         * 跑男 订单确认送达
         * 3->4 等待用户确认收货
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function confirmedDelivery()
        {
            (new IDMustBePositiveInt())->goCheck();
            $uid   = Token::getCurrentUid();
            $order = (new OrderModel())->where(['state' => 3, 'order_account_id' => $uid])->get(input('post.id'));
            if (!$order) {
                throw new MissException(['msg' => '当前订单不存在', 'errorCode' => 60006]);
            }
            $order->state = 4;
            $order->save();
            return new SuccessMessage();
        }

        /**
         * 用户端确认收货
         * 4->5 用户人确认收货 订单完成 打款到跑男端
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function confirmReceipt()
        {
            (new IDMustBePositiveInt())->goCheck();
            $uid   = Token::getCurrentUid();
            $order = (new OrderModel())->where(['state' => 4, 'account_id' => $uid])->get(input('post.id'));
            if (!$order) {
                throw new MissException(['msg' => '当前订单不存在', 'errorCode' => 60006]);
            }
            $order->state = 5;
            //确认送达时间
            $order->complete_time = time();
            $order->save();
            //获取跑男用户
            $receiver        = (new Account())->get($order->order_account_id);
            $receiver->money += $order->order_account_price;
            $receiver->save();
            //将订单金额增加到跑男金额
            return new SuccessMessage();
        }

        /**
         * 获取跑男端未完成订单
         *
         * @param $page
         * @param $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function incompleteOrders($page, $size)
        {
            (new PagingParameter())->goCheck();
            $uid          = Token::getCurrentUid();
            $pagingOrders = OrderModel::incompleteOrders($uid, $page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }

        /**
         * 获取跑男端已完成订单
         *
         * @param $page
         * @param $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function completedOrder($page, $size)
        {
            (new PagingParameter())->goCheck();
            $uid          = Token::getCurrentUid();
            $pagingOrders = OrderModel::completedOrder($uid, $page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }

        /**
         * 获取用户端进行中订单
         *
         * @param $page
         * @param $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function onGoingOrder($page, $size)
        {
            (new PagingParameter())->goCheck();
            $uid          = Token::getCurrentUid();
            $pagingOrders = OrderModel::onGoingOrder($uid, $page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }


        /**
         * 获取用户端已结束订单
         *  超时未支付 ，订单已完成
         *
         * @param $page
         * @param $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function endedOrder($page, $size)
        {
            (new PagingParameter())->goCheck();
            $uid          = Token::getCurrentUid();
            $pagingOrders = OrderModel::endedOrder($uid, $page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }

        //获取所有用户订单

        public function getAllOrder($page, $size){
            (new PagingParameter())->goCheck();
            $pagingOrders = OrderModel::getAllOrders($page, $size);
            if ($pagingOrders->isEmpty()) {
                return [
                    'current_page' => $pagingOrders->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $pagingOrders->toArray();
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data'         => $data,
            ];
        }



        /**
         * 联系跑男电话+1
         * @return SuccessMessage
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function callPhoneByAccount()
        {
            (new IDMustBePositiveInt())->goCheck();
            $id                  = input("post.id");
            $account             = Account::get($id);
            $account->call_count = ['inc', 1];
            $account->save();
            return new SuccessMessage();
        }

        /**
         * 获取所有营业额
         *
         */
        public function getAllMoney(){
            $money=OrderModel::where('state',2)->sum('order_price');
            return $money;
        }


        /**
         * 取消订单
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         */
        public function cancleOrder(){
            (new IDMustBePositiveInt())->goCheck();

            $uid   = Token::getCurrentUid();
            //已支付未接单可取消订单
            $order = (new OrderModel())->where('state', 2)->get(input('post.id'));
            if (!$order) {
                throw new MissException(['msg' => '当前订单不合法', 'errorCode' => 60006]);
            }
            //将订单状态改为退款申请中

            $order->state=7;

            $order->save();

            return new SuccessMessage();
        }

        /**
         * 申请退款
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception
         */
        public function refund(){
            (new IDMustBePositiveInt())->goCheck();
//            $uid   = Token::getCurrentUid();

            $refund=new RefundServer(input('post.id'));

            return $refund->refund();

        }



    }